package com.byq.mm.smartlib;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;

import com.byq.mm.abstractx.cluster.client.ClientDeviceManager;
import com.byq.mm.abstractx.cluster.server.ServerDeviceManager;
import com.byq.mm.abstractx.device.Device;
import com.byq.mm.smartlib.activity.ConversationList;
import com.byq.mm.smartlib.activity.DeviceActivity;
import com.byq.mm.smartlib.activity.ServerManagerActivity;
import com.byq.mm.smartlib.activity.ServiceSettingsActivity;
import com.byq.mm.smartlib.activity.Settings;
import com.byq.mm.smartlib.application.SmartApplication;
import com.byq.mm.smartlib.cluster.activity.client.DeviceActivityManager;


import com.byq.mm.common.engine.ConnectionManager;
import com.byq.mm.common.engine.Contact;
import com.byq.mm.smartlib.engine.PresenceMap;
import com.byq.mm.smartlib.service.SmartConnectionService;
import com.byq.mm.smartlib.engine.AndroidAccountManager;
import com.byq.mm.smartlib.tools.ModeArrayAdapter;
import com.byq.mm.smartlib.tools.RosterAdapter;

import java.util.ArrayList;
import java.util.List;

public class SmartAgent extends Activity implements View.OnClickListener,
		ExpandableListView.OnChildClickListener{

	private static final int REQUEST_SETTINGS = 2008;
	private static final int RESULT_CHATLIST = 4003;

	private static final String TAG = "Jabberoid.class";

	private BroadcastReceiver listReceiver;


	private ProgressDialog pd = null;

	private ExpandableListView contactList;
	private ImageView exit;
	private ImageView btnSettings;
	private ImageView btnAddUser;
	private ImageView btnEditStatusMsg;
	private ImageView serverCenter;
	private ImageView onoff;
	private Spinner spin;

	private BaseExpandableListAdapter contactListAdapter;
	SmartApplication application;
	private ImageView btnService;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.smart_agent);
		application = (SmartApplication) this.getApplication();

		contactList = (ExpandableListView) findViewById(R.id.contactList);

		contactList.setOnChildClickListener(this);
		contactListAdapter = new RosterAdapter(this, application);
		contactList.setAdapter(contactListAdapter);



		exit = (ImageView) findViewById(R.id.exit);
		exit.setOnClickListener(this);
		btnSettings = (ImageView) findViewById(R.id.butSettings);
		btnSettings.setOnClickListener(this);
		btnAddUser = (ImageView) findViewById(R.id.addUser);
		btnAddUser.setOnClickListener(this);
		btnEditStatusMsg = (ImageView) findViewById(R.id.butEditStatus);
		btnEditStatusMsg.setOnClickListener(this);
		serverCenter = (ImageView) findViewById(R.id.butShowOffline);
		serverCenter.setOnClickListener(this);
		

		getResources().getStringArray(R.array.statusSpinner);
		onoff = (ImageView) findViewById(R.id.onoff);
		onoff.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				boolean logged = getConnectionManager()
						.isLoggedIn();
				if (!logged) {
					login();
				} else {
					getConnectionManager().logout();
				}

			}
		});
		spin = (Spinner) findViewById(R.id.status);

		spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent, View v,
							int position, long id) {

						Contact.Mode mode = (Contact.Mode) v.getTag();

//						getConnectionManager().setPresenceMode(
//								null, mode);

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}

				});

		PresenceMap map = new PresenceMap(this);
		ModeArrayAdapter aa = new ModeArrayAdapter(this,
				R.layout.spinner_view_dropdown, map.getModeNames(),
				map.modeIcons, map.modes); // (this,R.layout.spinner_view,R.array.statusSpinner);
		spin.setAdapter(aa);
		spin.setPromptId(R.string.setYourStatus);

		registerForContextMenu(contactList);

		Intent aimConServ = new Intent(this, SmartConnectionService.class);
		aimConServ.setPackage(this.getPackageName());
		startService(aimConServ);
		
		registerAllReceiver();
		 updateView();
			boolean logged = getConnectionManager()
					.isLoggedIn();
			if(!logged)
				login();
		
	}
	
	void updateView(){
	
		if (pd!= null && pd.isShowing())
			pd.dismiss();
		if (getConnectionManager().isLoggedIn()){
			onoff.setImageResource(R.drawable.logout_bg);
			spin.setVisibility(View.VISIBLE);
		}
		else{
			onoff.setImageResource(R.drawable.login_bg);
			spin.setVisibility(View.GONE);
		}
		contactListAdapter.notifyDataSetChanged();
		if (contactList.getCount() != 0) {
			contactList.expandGroup(0);
		}
	}


	boolean login(){
		boolean valid = new AndroidAccountManager(SmartAgent.this).valid();
		if (!valid){
			Toast.makeText(SmartAgent.this, R.string.invalid_settings, Toast.LENGTH_SHORT).show();
			return false;
		}
		progressD();
		getConnectionManager().login(false);
		return true;
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		unRegisterAllReceiver();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo info) {
		super.onCreateContextMenu(menu, v, info);
		ExpandableListContextMenuInfo elcmi = (ExpandableListContextMenuInfo) info;
		int grpPos = ExpandableListView
				.getPackedPositionGroup(elcmi.packedPosition);
		int childPos = ExpandableListView
				.getPackedPositionChild(elcmi.packedPosition);
		if(childPos < 0)
			return;
		Contact re = (Contact) contactListAdapter.getChild(grpPos,
				childPos);
		String jid = re.getTransport();// groupedContactList.get(grpPos).get(childPos).get("contactJid").toString();

		menu.setHeaderTitle(jid);
		ListView list = (ListView)v;


		menu.add(Menu.NONE, 3, Menu.NONE,  R.string.offer_defination);
		menu.add(Menu.NONE, 0, Menu.NONE, R.string.openChat);
		menu.add(Menu.NONE, 1, Menu.NONE,  R.string.delete_contact);
		menu.add(Menu.NONE, 2, Menu.NONE,  R.string.request_defination);

		menu.add(Menu.NONE, 4, Menu.NONE,  R.string.remove_defination);
		menu.add(Menu.NONE, 5, Menu.NONE, R.string.contact_modification);

	}

	void offer(Contact contact) {
		ServerDeviceManager dm = application.getAndroidSmartEngine().getCoreEngine().getServerDeviceManager();
		dm.offer(contact.getTransport());
	}

	void deleteContact(Contact contact) {

			application.getAndroidSmartEngine().getXmppEngine().getContactManager().delete(contact);
			Toast.makeText(this, "Deleted Successfully!", Toast.LENGTH_LONG);
	
	}

	void delete(final Contact contact) {
		new AlertDialog.Builder(this).setTitle(
				getResources().getText(R.string.confirm_delete))
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(!getConnectionManager().isLoggedIn()){
							Toast.makeText(SmartAgent.this, R.string.transport_unavailable, Toast.LENGTH_SHORT).show();
							return;
						}
						deleteContact(contact);

					}
				}).setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						}).show();
		return;
	}

	void request(Contact contact) {
		ServerDeviceManager dm = application.getAndroidSmartEngine().getCoreEngine().getServerDeviceManager();
		dm.request(contact.getTransport());
		return;
	}
	
void contactModification(final Contact contact) {
		
	LayoutInflater layoutInflater = LayoutInflater.from(this);
	View view = layoutInflater.inflate(R.layout.nickname_dialog, null);
	final EditText newUser = (EditText) view
			.findViewById(R.id.addUserDialog_entry);
	newUser.setText(contact.getTransport());
	final EditText nick = (EditText) view
			.findViewById(R.id.addUserDialog_nick);
	nick.setText(contact.getName());
	final Spinner groupSwitcher = (Spinner) view
			.findViewById(R.id.addUserDialog_groupSwitcher);
	ArrayAdapter<Object> aa = new ArrayAdapter<Object>(this,
			android.R.layout.simple_spinner_item,new String[0]);
	groupSwitcher.setAdapter(aa);
	new AlertDialog.Builder(this).setTitle(
			getResources().getText(R.string.contact_modification)).setView(view)
			.setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
							if(!getConnectionManager().isLoggedIn()){
								Toast.makeText(SmartAgent.this, R.string.transport_unavailable, Toast.LENGTH_SHORT).show();
								return;
							}
							application.getAndroidSmartEngine().getXmppEngine().getContactManager().nickName(contact.getTransport(), nick.getText().toString());
							
						}
					}).setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {

						}
					}).show();
	
	}
	void removeDefination(final Contact contact) {
		
		
		new AlertDialog.Builder(this).setTitle(
				getResources().getText(R.string.confirm_remove_defination))
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						ClientDeviceManager dm = application.getAndroidSmartEngine().getCoreEngine().getClientDeviceManager();
						dm.removeDefination(contact.getTransport());
						return;

					}
				}).setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						}).show();
		return;
	
	}
	void exit() {
		
		
		new AlertDialog.Builder(this).setTitle(
				getResources().getText(R.string.confirm_exit))
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent aimConServ = new Intent(SmartAgent.this, SmartConnectionService.class);
						aimConServ.setPackage(SmartAgent.this.getPackageName());
						SmartAgent.this.stopService(aimConServ);
						SmartAgent.this.finish();
						System.exit(0);
						return;

					}
				}).setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						}).show();
		return;
	
	}
	public boolean onContextItemSelected(MenuItem item) {
		ExpandableListContextMenuInfo elcmi = (ExpandableListContextMenuInfo) item
				.getMenuInfo();
		int groupPosition = ExpandableListView
				.getPackedPositionGroup(elcmi.packedPosition);
		int childPosition = ExpandableListView
				.getPackedPositionChild(elcmi.packedPosition);
		Contact re = (Contact) contactListAdapter.getChild(
				groupPosition, childPosition);
		switch (item.getItemId()) {
		case 0:
			startChat(re.getTransport());// groupedContactList.get(groupPosition).get(childPosition).get("contactJid").getJid());
			break;

		case 1:
			delete(re);// groupedContactList.get(groupPosition).get(childPosition).get("contactJid").getJid());
			break;
		case 2:
			request(re);// groupedContactList.get(groupPosition).get(childPosition).get("contactJid").getJid());
			break;
		case 3:
			offer(re);// groupedContactList.get(groupPosition).get(childPosition).get("contactJid").getJid());
			break;
		case 4:
			removeDefination(re);// groupedContactList.get(groupPosition).get(childPosition).get("contactJid").getJid());
			break;
		case 5:
			
			contactModification(re);// groupedContactList.get(groupPosition).get(childPosition).get("contactJid").getJid());

		}
		return true;
	}

	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {

		Contact re = (Contact) contactListAdapter.getChild(
				groupPosition, childPosition);
		Device d = application.getAndroidSmartEngine().getCoreEngine().getClientDeviceManager().getRootDevice(
				re.getTransport());
		if (d == null)
			startChat(re.getTransport());//

		else {
			if(!d.getSupportedClusters().isEmpty()){

				Intent intent = new Intent();
				intent.setPackage(SmartAgent.this.getPackageName());
				Class ac =  DeviceActivityManager.getDeviceActivity(d.getType());
				if(ac == null)
					ac = DeviceActivity.class;
				intent.setClass(this, ac);
				intent.putExtra("globalId", d.getGlobalId());

				startActivity(intent);
			}
		}
		return true;
	}

	private void registerAllReceiver() {
		IntentFilter listFilter = new IntentFilter();
		listFilter.addAction(SmartActionConstants.CONNECTION_CLOSED);
		listFilter.addAction(SmartActionConstants.DEVICE_CHANGED);
		listFilter.addAction(SmartActionConstants.PRESENCE_CHANGED);
		listFilter.addAction(SmartActionConstants.LOGIN_SUCCESS);
		listFilter.addAction(SmartActionConstants.LOGIN_FAIL);
		listFilter.addAction(SmartActionConstants.LOGOUT);
		listFilter.addAction(SmartActionConstants.CONNECTION_ERROR_CLOSED);
		listReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				Log.d("fff",intent.getAction());
				updateView();
				Bundle ex = intent.getExtras();
				if(ex == null)
					return;
				String msg = intent.getExtras().getString("message");
				if(msg != null)
					Toast.makeText(SmartAgent.this, msg, Toast.LENGTH_SHORT).show();
				
			}
		};

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			registerReceiver(listReceiver, listFilter,RECEIVER_NOT_EXPORTED);
		}
	}

	private void unRegisterAllReceiver() {

			unregisterReceiver(listReceiver);

	}

	private void progressD() {
		if(pd != null)
			pd.dismiss();
		pd = ProgressDialog.show(this, this.getString(R.string.connecting),
				this.getString(R.string.connecting_info)
						+ new AndroidAccountManager(this).getUser());
	}


	public void onClick(View v) {
		if (v == exit) {
			exit();
		}else if (v == btnSettings) {
			Intent i = new Intent(this, Settings.class);
			i.setPackage(SmartAgent.this.getPackageName());
			startActivityForResult(i, REQUEST_SETTINGS);
		} else if (v == btnAddUser) {
			LayoutInflater layoutInflater = LayoutInflater.from(this);
			View view = layoutInflater.inflate(R.layout.add_user_dialog, null);
			final EditText newUser = (EditText) view
					.findViewById(R.id.addUserDialog_entry);
			final EditText nick = (EditText) view
					.findViewById(R.id.addUserDialog_nick);

			final Spinner groupSwitcher = (Spinner) view
					.findViewById(R.id.addUserDialog_groupSwitcher);
			ArrayAdapter<Object> aa = new ArrayAdapter<Object>(this,
					android.R.layout.simple_spinner_item,new String[0]);
			groupSwitcher.setAdapter(aa);
			new AlertDialog.Builder(this).setTitle(
					getResources().getText(R.string.add_user)).setView(view)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if(!getConnectionManager().isLoggedIn()){
										Toast.makeText(SmartAgent.this, R.string.transport_unavailable, Toast.LENGTH_SHORT).show();
										return;
									}
									String user = newUser.getText().toString();
									if(user == null || user.trim().equals(""))
										return;
									if(user.indexOf("@") == -1){
										String service = application.getAndroidSmartEngine().getAccountManager().getService();
										user = user + "@" + service;
									}
									String nick = newUser.getText().toString();
									if (nick.equals("")) {
										
									}
									Contact c = new Contact();
									c.setTransport(user);
									c.setName(nick);

										application.getAndroidSmartEngine().getXmppEngine().getContactManager().add(c);
									
								}
							}).setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {

								}
							}).show();

		} else if (v == btnEditStatusMsg) {

			LayoutInflater layoutInflater = LayoutInflater.from(this);
			View view = layoutInflater.inflate(R.layout.status_message_dialog,
					null);
			final EditText msg = (EditText) view
					.findViewById(R.id.statusMessageDialog_msg);
			final Spinner switcher = (Spinner) view
					.findViewById(R.id.statusMessageDialog_msgSwitcher);
			ArrayAdapter<Object> aa = new ArrayAdapter<Object>(this,
					android.R.layout.simple_spinner_item,
					getLastStatusMessages().toArray());
			switcher.setAdapter(aa);

			new AlertDialog.Builder(this).setTitle(
					getResources().getText(R.string.add_status_message))
					.setView(view).setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									String user = msg.getText().toString();
									Object si = switcher.getSelectedItem();

								}
							}).setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {

								}
							}).show();

		} else if (v == serverCenter) {

			Intent i = new Intent();
			i.setPackage(SmartAgent.this.getPackageName());
			i.setClass(this, ServerManagerActivity.class);
			this.startActivity(i);
		}
	 else if (v == btnService) {

		Intent i = new Intent();
		i.setPackage(SmartAgent.this.getPackageName());
		i.setClass(this, ServiceSettingsActivity.class);
		this.startActivity(i);
	}
	}


	private void startChat(String jid) {
		finishActivity(RESULT_CHATLIST);
		Intent i = new Intent(this, ConversationList.class);
		i.setPackage(SmartAgent.this.getPackageName());
		i.putExtra("startChat", true);
		i.putExtra("jid", jid);
		startActivityForResult(i, RESULT_CHATLIST);
	}

	public void setStatusMessage(String message) {
		getConnectionManager().pushMessage(message);

	}

	public List<String> getLastStatusMessages() {
		List<String> list = application.getAndroidSmartEngine().getXmppEngine().getLiteStore().getLastStatusMessages();

		if (list == null) {
			list = new ArrayList<String>();
			list.add("");
		}

		return list;
	}
	ConnectionManager getConnectionManager(){
		return application.getAndroidSmartEngine().getXmppEngine().getConnectionManager();
	}

}